package com.wzz.common.app;

import android.app.Dialog;
import android.content.Context;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * @author 梁天刚 <br/>
 *	查询对话框
 */
public class SearchDialog extends Dialog implements View.OnClickListener{
	private EditText search;
	private ImageView button;
	private android.view.View.OnClickListener listener;
	private static final String TAG = "SearchDialog";

	public SearchDialog(Context context) {
		super(context);
		initView(context);
		
		getWindow().getDecorView().setBackgroundColor(0);
	}
	
	private void initView(Context context){
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		LinearLayout content = new LinearLayout(context);
		content.setGravity(Gravity.CENTER);
		content.setPadding(0, 0, 0, 0);
		search = new EditText(context);
		search.setEms(10);
		search.setMaxLines(1);
		LinearLayout.LayoutParams svl = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
		svl.setMargins(0, 0, 0, 0);
		content.addView(search, svl);
		button = new ImageView(context);
		button.setImageResource(android.R.drawable.ic_menu_search);
		button.setBackgroundResource(android.R.drawable.edit_text);
		button.setOnClickListener(this);
		content.addView(button, svl);
		getWindow().setContentView(content);
		
		format();
	}
	
	/**
	 * 将dialog的位置置于屏幕顶部中间
	 */
	public void format(){
	    Display display = getWindow().getWindowManager().getDefaultDisplay();
	    Window win = getWindow();
	    WindowManager.LayoutParams wl = win.getAttributes();
	    wl.y = 0 - display.getHeight() / 2;
	    win.setAttributes(wl);
	}
	

	@Override
	public void onClick(View v) {
		dismiss();
		if(listener != null){
			listener.onClick(v);
		}
	}
	
	public void setButtonListener(android.view.View.OnClickListener listener){
		this.listener = listener;
	}
	
	public String getSearchText(){
		return search.getText().toString();
	}
	
	public void setText(String text){
		search.setText(text);
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(event.getKeyCode() == KeyEvent.KEYCODE_SEARCH){
			return true;
		}
		return super.dispatchKeyEvent(event);
	}
}
